<template>
  <div>
    <!-- 流失客户预警 -->
    <el-table-form ref="form" :model="query">
      <el-form-item>
        <el-input-number v-model="query.dayNum" :controls="false" :precision="0" size="mini" style="width: 80px;" />
        <span style="width: 10px; height: 19px; margin: 0 4px;">~</span>
        <el-input-number v-model="query.dayNumEnd" :controls="false" :precision="0" size="mini" style="width: 80px;" />
        <span style="width: 160px; margin-left: 4px;">天未订气</span>
      </el-form-item>
      <el-form-item :table-form-merge="2" class="merge-item" label="最后订气时间:">
        <el-date-picker
          v-model="date"
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[moment().format('HH:mm:ss'), moment().format('HH:mm:ss')]"
        />
      </el-form-item>
      <el-form-item label="客户类型:">
        <el-select v-model="query.csmType" clearable filterable placeholder="请选择">
          <el-option
            v-for="item in customerTypeMap"
            :key="item.value"
            :label="item.desc"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="客户状态:">
        <el-select v-model="query.csmStatus" filterable clearable placeholder="请选择">
          <el-option
            v-for="item in customerStatusMap"
            :key="item.value"
            :label="item.desc"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="所属机构:">
        <el-tree-select
          v-model="query.orgSNNo"
          clearable
          class="tree-select"
          :popover-width="360"
          :select-params="{
            clearable: true,
            placeholder: '请选择',
            loading: $loadingPlugin.getTreeData
          }"
          :tree-params=" {
            'default-expand-all': true,
            'expand-on-click-node': false,
            'highlight-current': true,
            props:{
              value:'orgSNNo',
              label: 'orgName',
              disabled: 'disabled',
            },
            data: treeData
          }"
          @node-click="selectTreeChange"
          @select-clear="closeTree"
        />
      </el-form-item>
      <el-form-item label="销售员:">
        <el-select v-model="query.salesmanName" :loading="$loadingPlugin.getOwnersList" clearable filterable style="width: 100%;" placeholder="请选择">
          <el-option
            v-for="item in ownersList"
            :key="item.userId"
            :label="item.userName"
            :value="item.userId"
          />
        </el-select>
      </el-form-item>
      <template v-slot:btns>
        <el-button :loading="$loadingPlugin.fetchData" type="primary" icon="el-icon-search" @click="search">查询</el-button>
      </template>

    </el-table-form>
    <!-- 导出 -->
    <div>
      <el-button :loading="$loadingPlugin.exportFile" type="primary" icon="el-icon-folder-opened" @click="exportFile">导出</el-button>
    </div>
    <!-- 表格 -->
    <lb-table
      ref="lbTable"
      v-loading="$loadingPlugin.fetchData"
      v-el-height-adaptive-table="{bottomOffset:10}"
      class="table"
      border
      highlight-current-row
      element-loading-text="加载中"
      :column="tableData.column"
      :data="tableData.data"
      pagination
      :total="tableData.total"
      custom-column
      @fetch="fetchData"
    />
    <orderDetails ref="orderDetails" />
  </div>
</template>

<script>
  import OrderDetails from './components/OrderDetails'
  import { formatColumnMap, parseTime } from '@/utils'
  import { mergeAsyncFunc } from '@/utils/mergeAsyncFunc'
  import { queryLostCsmWarningList, queryMap, queryLostCsmWarningListExport, queryOwnersList } from '@/api'
  import getTreeData from '@/utils/jsonTree'
  import { mapGetters } from 'vuex'
  import moment from 'dayjs'

  const colorObj = { '1': 'color:#EA8511', '-1': 'color:red' }
  export default {
    name: 'lostCsmWarning',
    components: {
      OrderDetails
    },
    data() {
      return {
        moment,
        treeData: [],
        ownersList: [],
        customerTypeMap: [],
        customerStatusMap: [],
        customerQualityMap: [],
        date: [],
        query: {
          dayNum: 0,
          dayNumEnd: 30,
          csmType: '',
          csmStatus: '',
          orgSNNo: '',
          salesmanName: ''
        },
        tableData: {
          total: 0,
          column: [
            {
              prop: 'nearStationName',
              label: '门店名称',
              width: 150
            },
            {
              prop: 'csmCode',
              label: '客户编码'
            },
            {
              prop: 'csmName',
              label: '客户名称'
            },
            {
              prop: 'cardType',
              label: '客户类型',
              render: (h, { row }) => <span>{ row.csmType && formatColumnMap(this.customerTypeMap, 'value', row.csmType, 'desc') }</span>
            },
            {
              prop: 'csmQuality',
              label: '性质',
              render: (h, { row }) => <span>{ row.csmQuality ? formatColumnMap(this.customerQualityMap, 'value', row.csmQuality, 'desc') : '未知' }</span>
            },
            {
              prop: 'deposit',
              label: '押金',
              align: 'right',
              render: (h, { row }) => row.deposit && <span>{ row.deposit }</span>
            },
            {
              prop: 'csmRgPhone',
              label: '电话',
              width: 110
            },
            {
              prop: 'csmRgAddress',
              label: '地址',
              width: 220
            },
            {
              prop: 'salesmanName',
              label: '销售员'
            },
            {
              prop: 'totalGasCount',
              align: 'right',
              label: '订气总量',
              render: (h, { row }) => row.totalGasCount && <span>{ row.totalGasCount }</span>
            },
            {
              prop: 'creditRating',
              align: 'right',
              label: '信用度'
            },
            {
              prop: 'lastBuyDt',
              label: '最后订气时间',
              width: 160,
              render: (h, { row }) => <span>{ row.lastBuyDt && parseTime(row.lastBuyDt, '{y}-{m}-{d} {h}:{i}:{s}') }</span>
            },
            {
              prop: 'csmStatus',
              label: '客户状态',
              render: (h, { row }) => <span style={colorObj[row.csmStatus]}>{ row.csmStatus && formatColumnMap(this.customerStatusMap, 'value', row.csmStatus, 'desc') }</span>
            },
            {
              prop: 'createTime',
              label: '创建时间',
              width: 160,
              render: (h, { row }) => <span>{ row.createTime && parseTime(row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }</span>
            }
          ],
          data: []
        }
      }
    },
    computed: {
      ...mapGetters([
        'orgList', 'corpSettingData'
      ])
    },
    async created() {
      await Promise.all([this.queryOptionsMap(), this.getTreeData(), this.getOwnersList()])
    },
    methods: {
      _getQuery(obj) {
        const query = {}
        for (const key in obj) {
          if (obj.hasOwnProperty(key)) {
            if (obj[key] !== '') {
              query[key] = obj[key]
            }
          }
        }
        return query
      },
      async fetchData({ currentPage, pageSize }) {
        const query = {
          ...this._getQuery(this.query),
          currentPage,
          pageSize
        }
        if (this.date && this.date.length > 0) {
          query.lastBuyDt = moment(this.date[0]).format()
          query.lastBuyDtEnd = moment(this.date[1]).format()
        }
        const res = await queryLostCsmWarningList(query)
        this.tableData.data = res.data.rows
        if (currentPage === 1) this.tableData.total = res.data.total
      },
      // 获取所属机构数据
      async getTreeData() {
        const data = this.orgList.map(item => ({
          label: item.name,
          ...item
        }))
        this.treeData = getTreeData(data)
      },
      // 查询枚举
      async queryOptionsMap() {
        const [res1, res2, res3] = await Promise.all([mergeAsyncFunc(queryMap, { enumName: 'CustomerType' }), mergeAsyncFunc(queryMap, { enumName: 'CustomerStatus' }), mergeAsyncFunc(queryMap, { enumName: 'CustomerQuality' })])
        this.customerTypeMap = res1.data // 客户类型
        this.customerStatusMap = res2.data // 客户状态
        this.customerQualityMap = res3.data
      },
      // 选择所属机构
      selectTreeChange(value) {
        this.$set(this.query, 'salesmanName', '')
        this.getOwnersList(value.orgId)
      },
      closeTree(v) {
        this.$set(this.query, 'salesmanName', '')
        this.getOwnersList()
      },
      // 查询处理人列表
      async getOwnersList(org) {
        const res = await queryOwnersList({
          orgId: org || -1
        })
        this.ownersList = res.data
      },
      search() {
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      // 导出
      async exportFile() {
        const _this = this
        this.$confirm(`确定导出数据？`, '提示', {
          type: 'info'
        }).then(() => {
          const copyColumn = JSON.parse(JSON.stringify(this.tableData.column))
          copyColumn.pop()
          const str = {}
          copyColumn.forEach(item => {
            str[item.prop] = item.label
          })
          queryLostCsmWarningListExport({
            paramInfo: _this._getQuery(_this.query),
            kv: str // 表格列
          }).then((res) => {
            window.open(`${this.exportDomain}/page/export/frame?key=${res.data}`, '_blank')
          })
        })
      }
    }
  }
</script>

<style lang="scss" scoped>

</style>

